package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HuiyuanMapper;
import com.ruoyi.system.domain.Huiyuan;
import com.ruoyi.system.service.IHuiyuanService;
import com.ruoyi.common.support.Convert;

/**
 * 会员 服务层实现
 * 
 * @author ruoyi
 * @date 2019-07-16
 */
@Service
public class HuiyuanServiceImpl implements IHuiyuanService 
{
	private static final Logger log = LoggerFactory.getLogger(HuiyuanServiceImpl.class);
	@Autowired
	private HuiyuanMapper huiyuanMapper;

	/**
     * 查询会员信息
     * 
     * @param huiyuanId 会员ID
     * @return 会员信息
     */
    @Override
	public Huiyuan selectHuiyuanById(Integer huiyuanId)
	{
	    return huiyuanMapper.selectHuiyuanById(huiyuanId);
	}
	
	/**
     * 查询会员列表
     * 
     * @param huiyuan 会员信息
     * @return 会员集合
     */
	@Override
	public List<Huiyuan> selectHuiyuanList(Huiyuan huiyuan)
	{
	    return huiyuanMapper.selectHuiyuanList(huiyuan);
	}
	
    /**
     * 新增会员
     * 
     * @param huiyuan 会员信息
     * @return 结果
     */
	@Override
	public int insertHuiyuan(Huiyuan huiyuan)
	{
		//先判断有介绍人的情况
		if(huiyuan.getParentId()!=null){
			Huiyuan info = huiyuanMapper.selectHuiyuanById(huiyuan.getParentId());
			huiyuan.setAncestors(info.getAncestors()+","+huiyuan.getParentId());
		}else {//没有介绍人的情况
			huiyuan.setParentId(0);//0为没有推荐人，属于一级会员
			huiyuan.setAncestors("0");//当父节点没有或者会员属于一级会员，则祖级列表为0
		}

	    return huiyuanMapper.insertHuiyuan(huiyuan);
	}
	
	/**
     * 修改会员
     * 
     * @param huiyuan 会员信息
     * @return 结果
     */
	@Override
	public int updateHuiyuan(Huiyuan huiyuan)
	{
		if(huiyuan.getParentId()!=null) {
			Huiyuan info = huiyuanMapper.selectHuiyuanById(huiyuan.getParentId());
			if((StringUtils.isNotNull(info))){
				String ancestors = info.getAncestors() + "," +info.getParentId();
				huiyuan.setAncestors(ancestors);
				updateHuiyuanChildren(huiyuan.getParentId(),ancestors);
			}
		}
	    return huiyuanMapper.updateHuiyuan(huiyuan);
	}

	/**
	 * 修改会员子元素关系
	 * @param huiyuanId 会员ID
	 * @param ancestors 元素列表
	 */
	public void updateHuiyuanChildren(int huiyuanId,String ancestors){
		Huiyuan huiyuan = new Huiyuan();
		huiyuan.setParentId(huiyuanId);
		List<Huiyuan> huiyuans = huiyuanMapper.selectHuiyuanList(huiyuan);
		for(Huiyuan children:huiyuans){
			children.setAncestors(ancestors + "," +huiyuan.getParentId());
		}
		if(huiyuans.size()>0){
			huiyuanMapper.updateHuiyuanChildren(huiyuans);
		}
	}

	/**
     * 删除会员对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteHuiyuanByIds(String ids)
	{
		return huiyuanMapper.deleteHuiyuanByIds(Convert.toStrArray(ids));
	}
	
}
